package cn.shangtour.user.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import cn.shangtour.common.pojo.User;
import cn.shangtour.common.utils.CookieUtils;
import cn.shangtour.common.vo.SysResult;
import cn.shangtour.user.service.UserService;

@RestController
@RequestMapping("user/manage")
public class UserController {
	@Autowired
	private UserService userService;
	@RequestMapping("/checkUserName")
	public SysResult checkUsername(String passport){
		Integer exist=userService.checkUsername(passport);
		if(exist==0){
			return SysResult.ok();
		}else{
			return SysResult.build(201, "已存在", null);
			
		}
	}
	
	@RequestMapping("/save")
	public SysResult userSave(User user){
		try {
			userService.userSave(user);
			return SysResult.ok();
		} catch (Exception e) {
			e.printStackTrace();
			return SysResult.build(201, "", null);
		}
	}
	
	@RequestMapping("password")
	public SysResult setPassword(User user){
		
		try {
			userService.setPassword(user);
			return SysResult.ok();
		} catch (Exception e) {
			e.printStackTrace();
			return SysResult.build(201, "", null);
		}
	}
	
	
	@RequestMapping("login")
	public SysResult doLogin(User user,HttpServletRequest request,HttpServletResponse response){
		String ticket = userService.doLogin(user);
		if(StringUtils.isNotEmpty(ticket)){
			CookieUtils.setCookie(request, response, "EM_TICKET", ticket);
			return SysResult.ok();
		}else{
			return SysResult.build(201, "错误", null);
		}
	}
	@RequestMapping("query/{ticket}")
	public SysResult checkLoginUser(@PathVariable String ticket){
		String userJson = userService.queryUserJson(ticket);
		if(StringUtils.isNotEmpty(userJson)){
			return SysResult.build(200,"ok",userJson);
			
		}else{
			return SysResult.build(201, "", null);
		}
		
		
		
		
	}
	
	
	

	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
}
